#define _GNU_SOURCE // 声明可以使用扩展语法
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>  // gettid()是当前库的一个扩展语法 
#include "mqueue.h"
#include "string.h"

#define MAX_MQ_SIZE 100
#define MQ_LEN 10

char* mq_name1 = "/test_mq"; 
mqd_t mq_fd;

void * first_thread(void *arg)
{
    printf("first thread running... tid: %d\n", gettid());

    // 发送消息队列
    mq_send(mq_fd, "hello world", strlen("hello world") + 1, 0);

    printf("first thread send mqMsg ok\n");

    return NULL;
}

void * second_thread(void *arg)
{
    printf("second thread running... tid: %d\n", gettid());

    char mq_buf[MAX_MQ_SIZE];

    ssize_t len = mq_receive(mq_fd, mq_buf, MAX_MQ_SIZE, NULL);

    printf("second thread receive mqMsg ok, msg: %s ,len: %ld\n", mq_buf, len);


    return NULL;
}


int main(int argc, char *argv[])
{
    // 创建消息队列
    struct mq_attr attr;
    attr.mq_msgsize = MAX_MQ_SIZE;
    attr.mq_maxmsg = MQ_LEN;

    mq_fd = mq_open(mq_name1, O_CREAT | O_RDWR, 0644, &attr);

    // 创建线程
    pthread_t pid1, pid2;
    pthread_create(&pid1, NULL, first_thread, NULL);
    pthread_create(&pid2, NULL, second_thread, NULL);

    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);

    // 关闭消息队列
    mq_close(mq_fd);
    mq_unlink(mq_name1);

    return 0;
}